﻿using System.IO;
using System.Web;
using System.Web.Caching;
using System.Xml.Serialization;
using Report.Entity;
using Report.Properties;

namespace Report
{
    public class ImageSettingManager
    {
        public static ImageSettingManager Instance = new ImageSettingManager();
        //HttpRuntime runtime = new HttpRuntime();

        public ImageSettings ReadSettings()
        {
            var cachedItem = (ImageSettings)HttpRuntime.Cache.Get("ImageSettings");

            if (cachedItem != null) return cachedItem;

            var serializer = new XmlSerializer(typeof(ImageSettings));

            using (var sm = new StreamReader(Settings.Default.ImageSettings))
            {
                var settings = (ImageSettings)serializer.Deserialize(sm);

                HttpRuntime.Cache.Insert("ImageSettings", settings, new CacheDependency(((FileStream)sm.BaseStream).Name));

                sm.Close();

                return settings;
            }
        }

        public void RefreshSettings()
        {
            HttpRuntime.Cache.Remove("ImageSettings");
        }

        public ImageSetting ReadSettingByName(string name)
        {
            var settings = ReadSettings();

            return settings.GetByName(name);
        }

        public ImageSetting ReadSettingByUrl(string url)
        {
            var settings = ReadSettings();

            return settings.GetByUrl(url);
        }
    }
}